package com.zzt.java_doc_search.common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.boot.test.autoconfigure.web.servlet.WebDriverScope;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: panda
 * Date: 2025-07-08
 * Time: 18:04
 */
public class Utils {

    public static WebDriver driver = null;
    public WebDriverWait wait = null;

    public Utils(String url){
        // 调用 driver 对象
        driver = createDriver();

        driver.get(url);

    wait = new WebDriverWait(driver, Duration.ofSeconds(3));
    }

    /**
     * 获取驱动对象
     */
    public static WebDriver createDriver(){
        if (driver == null) {
            // 下载驱动
            WebDriverManager.chromedriver().setup();
            // 添加配置：允许访问所有的连接
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            // 创建驱动对象
            driver = new ChromeDriver(options);

            // 隐式等待-只等待页面元素
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    /**
     * 屏幕截图
     * 屏幕截图文件目录
     * ./src/test/java/images/
     *                       /2025-04-29/
     *                                  /test01-20123010.png
     *                                  /test02-20133510.png
     *                       /2025-04-30/
     *                                  /test01-20123010.png
     *                                  /test02-20133510.png
     * str:方法名/类名
     */
    public void screenShot(String str) throws IOException {
        // 年月日
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        // 时分秒
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        // 图片文件名：路径+图片名称
        // src/test/java/images/2025-04-29/test01-20123010.png
        String fileName = "./src/test/java/images/" + dirTime + "/" + str + "-" + fileTime + ".png";

        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, new File(fileName));
    }

    /**
     * 销毁driver对象——关闭浏览器
     */
    public static void quit() {
        if (driver != null) {
            driver.quit();
        }
    }
}
